package com.itheima.service.mongo.impl;

import cn.hutool.core.util.ObjectUtil;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.mongo.VisitorService;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.List;
import java.util.regex.Pattern;

@DubboService
public class VisitorServiceImpl implements VisitorService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    StringRedisTemplate redisTemplate;

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    @Override
    public List<Visitor> findVisitorsTop5(Long userId, Long lastAccessTime) {
        //1.创建条件对象(登陆者id,时间,排序,分页)
        Query query = new Query(Criteria.where("userId").is(userId).and("date").gte(lastAccessTime))
                .with(Sort.by(Sort.Order.desc("date")))
                .limit(5);

        //2.查询visitor表中前五条数据且返回
        return mongoTemplate.find(query,Visitor.class);
    }

    @Override
    public List<Visitor> queryVisitors(Long userId,String nickname) {
        //查询前5个访客数据，按照访问时间倒序排序
        //如果用户已经查询过列表，记录查询时间，后续查询需要按照这个时间往后查询
        //上一次查询列表的时间
        /*Long date = Convert.toLong(redisTemplate.opsForHash()
                .get(VISITOR_REDIS_KEY, String.valueOf(userId)));*/
        PageRequest pageRequest = PageRequest.of(0,5, Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        if (StringUtils.isNotEmpty(nickname)) {
            Pattern pattern = Pattern.compile("^.*"+nickname+".$",Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("nickname").regex(pattern));
        }
        /*if (ObjectUtil.isNotEmpty(date)) {
            query.addCriteria(Criteria.where("date").gte(date));
        }*/

        List<Visitor> visitorsList = mongoTemplate.find(query, Visitor.class);
        //查询每个来访用户的得分
        for (Visitor visitors : visitorsList) {
            Query queryScore = Query.query(Criteria.where("toUserId")
                    .is(userId).and("userId").is(visitors.getVisitorUserId()));
            RecommendUser recommendUser = mongoTemplate.findOne(queryScore, RecommendUser.class);
            if (ObjectUtil.isNotEmpty(recommendUser)){
                visitors.setScore(recommendUser.getScore());
            }else {
                //默认得分
                visitors.setScore(90d);
            }
        }
        return visitorsList;
    }


    @Override
    public PageBeanVo findHistoryList(Integer page, Integer pagesize, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
//        query.with(new Sort(Sort.Direction.DESC,"date"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Visitor> visitorsList = mongoTemplate.find(query, Visitor.class);
        long count = mongoTemplate.count(query, Visitor.class);
        System.out.println(visitorsList);
        return new PageBeanVo(page,pagesize,count,visitorsList);


    }

    @Override
    public String saveVisitor(Long userId, Long visitorUserId, String from) {
        return null;
    }

    @Override
    public List<Visitor> queryMyVisitor(Long userId) {
        return null;
    }
    private List<Visitor> queryList(Query query, Long userId){
        List<Visitor> visitorsList = this.mongoTemplate.find(query, Visitor.class);
        //查询每个来访用户的得分
        for (Visitor visitors : visitorsList) {

            Query queryScore = Query.query(Criteria.where("toUserId")
                    .is(userId).and("userId").is(visitors.getVisitorUserId())
            );
            RecommendUser recommendUser = this.mongoTemplate.findOne(queryScore, RecommendUser.class);
            if(ObjectUtil.isNotEmpty(recommendUser)){
                visitors.setScore(recommendUser.getScore());
            }else {
                //默认得分
                visitors.setScore(90d);
            }
        }

        return visitorsList;
    }
    @Override
    public PageInfo<Visitor> topVisitor(Long userId, Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize,
                Sort.by(Sort.Order.desc("date")));
        Query query = Query.query(Criteria.where("userId").is(userId)).with(pageRequest);
        List<Visitor> visitorsList = this.queryList(query, userId);

        PageInfo<Visitor> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(visitorsList);

        //记录当前的时间到redis中，在首页查询时，就可以在这个时间之后查询了
        String redisKey = VISITOR_REDIS_KEY;
        String hashKey = String.valueOf(userId);
        String value = String.valueOf(System.currentTimeMillis());
        this.redisTemplate.opsForHash().put(redisKey, hashKey, value);

        return pageInfo;
    }
}
